package com.example.mobile2021606163crw0514;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.EOFException;
import java.io.IOException;

import javax.security.auth.login.LoginException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    private TextView tvMainContent;
    private String urlString = "http://192.168.29.230:3000/news";
    private OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(urlString)
                        .build();

                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    String result = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMainContent.setText(result);
                        }
                    });
                    Log.i("TAG", result);
                }catch(Exception e){
                    e.printStackTrace();

                }
                //异常访问
//                call.enqueue(new Callback() {
//                    @Override
//                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//                    }
//
//                    @Override
//                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//
//                    }
//                });
            }
        }).start();
    }
    private void initView() {
        tvMainContent = (TextView) findViewById(R.id.tvMainContent);
    }
}